/*
 * Copyright (c) 2015 elion. All Rights Reserved.
 */
package com.guoyu.project.web.admin;

import com.google.common.collect.Maps;
import com.guoyu.project.common.utils.IpAddressUtils;
import com.guoyu.project.common.utils.SHA256Utils;
import com.guoyu.project.common.utils.TimeUtil;
import com.guoyu.project.common.web.APIResponse;
import com.guoyu.project.model.BanIp;
import com.guoyu.project.model.Manager;
import com.guoyu.project.service.BanIpService;
import com.guoyu.project.service.ManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 管理员,前端接口ManagerController
 *
 * @author: xblibo Sun Jun 07 17:40:03 CST 2015
 * @version 1.0
 */
@Controller
@RequestMapping("admin")
public class LoginController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private ManagerService managerService;

    @Autowired
    private BanIpService banIpService;

    /**
     * 跳转登录页面
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        return "admin/login";
    }

    /**
     * 登录
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public APIResponse<Manager> login(String userName, String passwd, HttpServletRequest request) {
//        Manager manager = managerService.login(userName, passwd);
//        if (manager == null) {
//            return APIResponse.returnFail("用户名或密码错误");
//        }
//        setManager(request, manager);
        long nowTime = new Date().getTime();
        // 判断是否是ip限制的
        String ipAddress = IpAddressUtils.getIpAddress(request);
        Map<String,Object> paramsIp = Maps.newHashMap();

        List<BanIp> banIpList = banIpService.queryBanIps(paramsIp);
        for(BanIp ip : banIpList){
            if(ip.getIp().equals(ipAddress)){
                return APIResponse.returnFail("该ip已被限制登陆，请联系管理员");
            }
        }
        Manager managerExist = managerService.userExist(userName);
        // 判断用户是否存在
        if(managerExist == null ){
            return APIResponse.returnFail("用户不存在");
        }
        // 是用两种加密方式加密，（md5和sha256）
        Manager manager;
        manager = managerService.loginByMD5(userName, passwd);
        if(manager == null){
            manager = managerService.login(userName, passwd);
        }
        if (manager == null) {
            int count = managerExist.getLoginNum();
            if(count > 5){
                managerExist.setLoginNum(0);
                managerService.update(managerExist);
                return APIResponse.returnFail("输入密码次数超过限制，请稍后再试");
            }
            managerExist.setLoginNum(count + 1);
            managerService.update(managerExist);
            return APIResponse.returnFail("密码错误,你还有"+(6 - (count + 1) + "")+"次机会！");
        }

        // 如果用户密码正确，先判断是否180天没有修改密码
        long time = manager.getPwdTime().getTime();
        int day = (int) ((nowTime - time) / (1000*3600*24));
        if( day > 180){
            return APIResponse.returnFail("距离上次修改密码已超过180天，您需要再次修改密码");
        }
        managerExist.setLoginNum(0);
        managerService.update(managerExist);
        setManager(request,manager);
        logger.info("管理员：{}登陆，登陆时间：{}，登陆ip：{}",userName, TimeUtil.getTimeFormat(), ipAddress);
        return APIResponse.returnSuccess();
    }

    @RequestMapping(value = "logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "admin/login";
    }

    @RequestMapping("index")
    public String index() {
        return "admin/index";
    }

    @RequestMapping("home")
    public String home(HttpServletRequest request, Model model) {
        managerService.queryById(1);
        return "admin/home";
    }

    /**
     * 180天  强制修改密码
     */
    @RequestMapping(value = "coerceEditPwd",method = RequestMethod.POST)
    @ResponseBody
    public APIResponse coerceEditPwd(String userName,String passwd,String newPasswd,HttpServletRequest request){

        Manager manager = null;
        manager = managerService.login(userName, passwd);

        if(manager == null){
            manager = managerService.loginByMD5(userName, passwd);
            if(manager == null) {
                return APIResponse.returnFail("原密码错误");
            }
        }

        manager.setPassword(SHA256Utils.getSHA256String(newPasswd));
        manager.setPwdTime(new Date());
        managerService.update(manager);
        return APIResponse.returnSuccess();
    }
}